# -*- coding: utf-8 -*-

### Imports ###
import xbmc
import re
import urllib

# logowanie
import weblogin
import gethtml
#

from common import *
from common import (_addon, fav__COMMON__list_fetcher)

### ##########################################################################
### ##########################################################################
SiteName = 'Diff-Anime  [v0.1.1]  [Anime]'
SiteTag = 'diff-anime'
mainSite = 'http://diff-anime.pl/'

__settings__ = xbmcaddon.Addon(id="plugin.video.diff-anime")
addonPath = __settings__.getAddonInfo('path')
iconSite = addonPath + '/art/icon.png'
fanartSite = addonPath + '/art/diff-fanart.png'
nexticon = addonPath + '/art/next.png'

# logowanie
login = addst('username', '')
password = addst('password', '')
logged_in = weblogin.doLogin(addonPath, login, password)
ciastko = addonPath
###

colors = {'0': 'white', '1': 'red', '2': 'blue', '3': 'green', '4': 'yellow', '5': 'orange', '6': 'lime', '7': '', '8': 'cornflowerblue', '9': 'blueviolet', '10': 'hotpink', '11': 'pink', '12': 'tan'}

CR = '[CR]'
MyAlphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
MyBrowser = ['User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3']

### #########################################################################
### #########################################################################
site = addpr('site', '')
section = addpr('section', '')
url = addpr('url', '')
sections = {'series': 'series', 'movies': 'movies'}
thumbnail = addpr('img', '')
fanart = addpr('fanart', '')
page = addpr('page', '')

### #########################################################################


def Browse_Page(url, page='', metamethod=''):
    html = nURL(url)
    Browse_Items(html, metamethod)
    eod()


def Browse_Items(html, metamethod='', content='tvshows', view='515'):
    if (len(html) == 0):
        return
    r = re.compile("</a><div class='con'><a href='/(.+?)'>(.+?)</a><p>").findall(html)
    ItemCount = len(r)
    if len(r) > 0:
        for _url, _name in r:
            strona = 'http://diff-anime.pl/' + _url
            html2 = nURL(strona)
            _name2 = _name
#  grafika
            image = re.compile("</div><div class='content'><div class='con'><a href='(.+?)' class='fbox'>").findall(html2)
            ItemCount = len(image)
            if len(image) > 0:
                for foto in image:
                    img = "http://diff-anime.pl" + foto
            else:
                    img = ""
#  fanart
            if "Nie dodano kadrów do tej serii." in html2:
                fanart = fanartSite
            else:
                    image2 = re.compile("<h2>Kadry</h2></div><div class='content'><a href='(.+?)' class='fbox'>").findall(html2)
                    ItemCount = len(image)
                    if len(image) > 0:
                        for _fanart in image2:
                            fanart = "http://diff-anime.pl" + _fanart
                    else:
                            fanart = img
#  opis
            opis = re.compile("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)</div>").findall(html2)
            ItemCount = len(opis)
            if len(opis) > 0:
                for desc in opis:
                    plot = unicode(desc,"utf-8")
            else:
                    opis = re.compile("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<").findall(html2)
                    ItemCount = len(opis)
                    if len(opis) > 0:
                        for desc in opis:
                            plot = unicode(desc,"utf-8")
                    else:
                            opis = re.compile("<div id='pDesc' class='panel'><div class='head'><h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<br />").findall(html2)
                            ItemCount = len(opis)
                            if len(opis) > 0:
                                for desc in opis:
                                    plot = unicode(desc,"utf-8")
                            else:
                                    plot = "Nie dodano jeszcze opisu do tej serii."
            labs = {}
            try:
                labs['plot'] = plot
            except:
                labs['plot'] = ''
###
            pars = {'mode': 'Episodes', 'site': site, 'section': section, 'title': _name2, 'url': strona, 'img': img, 'fanart': fanart}
            contextLabs = {'title': _name2, 'url': strona, 'img': img, 'fanart': fanart, 'todoparams': _addon.build_plugin_url(pars), 'site': site, 'section': section, 'plot': labs['plot']}
            if   section == 'movie':
                contextMenuItems = ContextMenu_Movies(contextLabs)
            elif section == 'series':
                contextMenuItems = ContextMenu_Series(contextLabs)
            else:
                contextMenuItems = []
            labs['title'] = _name2
            _addon.add_directory(pars, labs, is_folder=True, fanart=fanart, img=img, contextmenu_items=contextMenuItems, total_items=ItemCount)
# szukanie następnej strony
    npage = url[:-2] + str(int(url[-2:]) + 10)
    if -1 != html.find("div class='pagenav") and -1 != html.find("class='img"):
            _addon.add_directory({'mode': 'Page', 'site': site, 'section': section, 'url': npage, 'page': npage}, {'title': "Next page"}, is_folder=True, fanart=fanartSite, img=nexticon)
    set_view(content, view_mode=addst('tvshows-view'))


# listowanie odcinków
def Browse_Episodes(url, page='', content='episodes', view='515'):
    html = gethtml.get(url + '/odcinki', addonPath)
    htmlplot = gethtml.get(url , addonPath)
    html = messupText(html, ciastko, True, True)
    s = "#(.+?)</div><div class=.+?</div><div class='con3'><a href='(.+?)' class='i'>"
    matches = re.compile(s).findall(html)
    ItemCount = len(matches)
    if ItemCount > 0:
        for  _nazwa, _url in matches:
            _url2 = 'http://diff-anime.pl' + _url
            _name = 'Odcinek' + _nazwa
            _title = '' + _name
#  grafika
            image = re.compile("</div><div class='content'><div class='con'><a href='(.+?)' class='fbox'>").findall(html)
            ItemCount = len(image)
            if len(image) > 0:
                for foto in image:
                    img = "http://diff-anime.pl" + foto
            else:
                    img = ""
#  fanart
            if "Nie dodano kadrów do tej serii." in html:
                fanart = fanartSite
            else:
                image2 = re.compile("<h2>Kadry</h2></div><div class='content'><a href='(.+?)' class='fbox'>").findall(html)
                ItemCount = len(image)
                if len(image) > 0:
                    for _fanart in image2:
                        fanart = "http://diff-anime.pl" + _fanart
                else:
                        fanart = img
#  opis
            opis = re.compile("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)</div>").findall(htmlplot)
            ItemCount = len(opis)
            if len(opis) > 0:
                for desc in opis:
                    plot = unicode(desc,"utf-8")
            else:
                    opis = re.compile("<h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<").findall(htmlplot)
                    ItemCount = len(opis)
                    if len(opis) > 0:
                        for desc in opis:
                            plot = unicode(desc,"utf-8")
                    else:
                            opis = re.compile("<div id='pDesc' class='panel'><div class='head'><h2>Opis anime</h2></div><div class='content'><div class='con'>(.+?)<br />").findall(htmlplot)
                            ItemCount = len(opis)
                            if len(opis) > 0:
                                for desc in opis:
                                    plot = unicode(desc,"utf-8")
                            else:
                                    plot = ""
            labs = {}
            try:
                labs['plot'] = plot
            except:
                labs['plot'] = ''
#  wyciąganie linku do mp4
            html2 = gethtml.get(_url2, addonPath)
            _link = re.compile("'file': '(.+?)',").findall(html2)
            ItemCount = len(_link)
            if len(_link) > 0:
                for link in _link:
                    strona = link.replace(' ', '%20')
###
            contextLabs = {'title': _name, 'year': '0000', 'url': _url2, 'img': img, 'fanart': fanart, 'DateAdded': '', 'plot': labs['plot']}
            contextMenuItems = ContextMenu_Episodes(labs=contextLabs)
            pars = {'mode': 'PlayFromHost', 'site': site, 'section': section, 'title': _name, 'url': strona, 'img': img, 'fanart': fanart}
            labs['title'] = _title
            _addon.add_directory(pars, labs, is_folder=False, fanart=fanart, img=img, contextmenu_items=contextMenuItems, total_items=ItemCount)
    set_view(content, int(addst('links-view')))
    eod()


#  lista ABC
def Browse_AZ():
    if section == 'series':
        tUrl = mainSite + 'lista-anime'
        scolor = colors['2']
        _addon.add_directory({'mode': 'Page', 'site': site, 'section': section, 'url': tUrl + '?letter=0&rowstart=00'}, {'title': '#'}, is_folder=True, fanart=fanartSite, img=addonPath + '/art/znak.png')
        for az in MyAlphabet:
            _addon.add_directory({'mode': 'Page', 'site': site, 'section': section, 'url': tUrl + '?letter='+ az + '&rowstart=00' }, {'title': az}, is_folder=True, fanart=fanartSite, img=addonPath + '/art/'+ az +'.png')
    if (len(addst('username' '')) == 0) or (len(addst('password', '')) == 0):
        d = xbmcgui.Dialog()
        d.ok('Komunikat', "Musisz się zalogować, aby móc oglądać odcinki.")
    set_view('list', view_mode=addst('default-view'))
    eod()


#  ulubione
def Fav_List(site='',section='',subfav=''):
    debob(['test1',site,section,subfav])
    favs=fav__COMMON__list_fetcher(site=site,section=section,subfav=subfav)
    ItemCount=len(favs)
    debob('test2 - '+str(ItemCount))
    if len(favs)==0: myNote('Favorites','None Found'); eod(); return
    debob(favs)
    for (_name,_year,_img,_fanart,_Country,_Url,_plot,_Genres,_site,_subfav,_section,_ToDoParams,_commonID,_commonID2) in favs:
        if _img > 0: img=_img
        else: img=iconSite
        if _fanart > 0: fimg=_fanart
        else: fimg=fanartSite
        debob('_ToDoParams'); debob(_ToDoParams)
        pars=_addon.parse_query(_ToDoParams)
        debob('pars'); debob(pars)
        _title=cFL_(_name,'white')
        if (len(_year) > 0) and (not _year=='0000'): _title+=cFL('  ('+cFL(_year,'deeppink')+')','pink')
        if len(_Country) > 0: _title+=cFL('  ['+cFL(_Country,'deeppink')+']','pink')

        contextLabs={'title':_name,'year':_year,'img':_img,'fanart':_fanart,'country':_Country,'url':_Url,'plot':_plot,'genres':_Genres,'site':_site,'subfav':_subfav,'section':_section,'todoparams':_ToDoParams,'commonid':_commonID,'commonid2':_commonID2}
        ##contextLabs={'title':_name,'year':'0000','url':_url,'img':img,'fanart':fimg,'DateAdded':'','todoparams':_addon.build_plugin_url(pars),'site':site,'section':section}
        contextMenuItems=ContextMenu_Favorites(contextLabs)
        #contextMenuItems=[]
        _addon.add_directory(pars,{'title':_title,'plot':_plot},is_folder=True,fanart=fimg,img=img,total_items=ItemCount,contextmenu_items=contextMenuItems)
        #
    #
    if 'movie' in section.lower(): content='movies'
    else: content='tvshows'
    set_view(content,view_mode=int(addst('tvshows-view'))); eod()


def SubMenu():
    if section == 'series':
        _addon.add_directory({'mode': 'AZ', 'site': site, 'section': section}, {'title': "Lista anime A-Z."}, is_folder=True, fanart=fanartSite, img=iconSite)
# ulubione
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.1.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '2'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.2.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '3'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.3.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
        _addon.add_directory({'mode': 'FavoritesList', 'site': site, 'section': section, 'subfav': '4'}, {'title': cFL_(ps('WhatRFavsCalled') + addst('fav.tv.4.name'), ps('cFL_color3'))}, fanart=fanartSite, img=iconSite)
    set_view('list', view_mode=addst('default-view'))
    eod()


def SectionMenu():
        _addon.add_directory({'mode': 'SubMenu', 'site': site, 'section': 'series'}, {'title': 'Anime Series'}, is_folder=True, fanart=fanartSite, img=iconSite)
        set_view('list', view_mode=addst('default-view'))

        eod()


### ############################################################################################################
def mode_subcheck(mode='',site='',section='',url=''):
    deb('mode',mode);
    if (mode=='SectionMenu'):         SectionMenu()
    elif (mode=='') or (mode=='main') or (mode=='MainMenu'): SectionMenu()
    elif (mode=='SubMenu'):             SubMenu()
    elif (mode=='Page'):                     Browse_Page(url=url,page=page,metamethod=addpr('metamethod','')) #(site,section)
    elif (mode=='Episodes'):             Browse_Episodes(url,page)
    elif (mode=='nextpage'):             Browse_Episodes(url,page)


    elif (mode=='AZ'):                         Browse_AZ()

    elif (mode=='PlayFromHost'):     PlayFromHost(url)

    elif (mode=='FavoritesList'): Fav_List(site=site,section=section,subfav=addpr('subfav',''))
    ##

    elif (mode=='PlayFromHost'):                 PlayFromHost(url)
    elif (mode=='ResolverSettings'):         import urlresolver; urlresolver.display_settings()  ## Settings for UrlResolver script.module.


    elif (mode=='cFavoritesEmpty'):      fav__COMMON__empty( site=site,section=section,subfav=addpr('subfav','') ); xbmc.executebuiltin("XBMC.Container.Refresh");
    elif (mode=='cFavoritesRemove'):  fav__COMMON__remove( site=site,section=section,subfav=addpr('subfav',''),name=addpr('title',''),year=addpr('year','') )
    elif (mode=='cFavoritesAdd'):          fav__COMMON__add( site=site,section=section,subfav=addpr('subfav',''),name=addpr('title',''),year=addpr('year',''),img=addpr('img',''),fanart=addpr('fanart',''),plot=addpr('plot',''),commonID=addpr('commonID',''),commonID2=addpr('commonID2',''),ToDoParams=addpr('todoparams',''),Country=addpr('country',''),Genres=addpr('genres',''),Url=url ) #,=addpr('',''),=addpr('','')
    elif (mode=='AddVisit'):
        try: visited_add(addpr('title')); RefreshList();
        except: pass
    elif (mode=='RemoveVisit'):
        try: visited_remove(addpr('title')); RefreshList();
        except: pass
    elif (mode=='EmptyVisit'):
        try: visited_empty(); RefreshList();
        except: pass
    elif (mode=='refresh_meta'):            refresh_meta(addpr('video_type',''),TagAnimeName(addpr('title','')),addpr('imdb_id',''),addpr('alt_id',''),addpr('year',''))
    else: myNote(header='Site:  "'+site+'"',msg=mode+' (mode) not found.'); import mMain
    #

mode_subcheck(addpr('mode',''),addpr('site',''),addpr('section',''),addpr('url',''))
### ############################################################################################################
### ############################################################################################################
